<template>
  <div>
    <el-button type="primary" size="large" @click="handleClick"
      >打开文件夹目录</el-button
    >
    <section>
      <nav>
        <h3 class="header_title">目录</h3>
        <el-input
          v-model="inputValue"
          placeholder=""
          clearable
          @input="handleInput"
        ></el-input>
        <div class="floder content">
          <SlideMenu
            :fileMenu="fileMenu"
            @selectHandleItem="selectHandleItem"
          ></SlideMenu>
        </div>
      </nav>
      <main>
        <h3 class="header_title">文件内容</h3>
        <div class="content">
          <pre>
              <code class="language-javascript">
                {{ fileContent }}
              </code>
            </pre>
        </div>
      </main>
    </section>
  </div>
</template>

<script lang="ts" setup>
// import SlideMenu from './SlideMenu.vue'
// import SlideMenu from './SlideMenu copy.vue'
import SlideMenu from './SlideMenu'
import type { FileMenu } from './types'
import { useFloderMenuStore } from '@/stores/index'
import {
  processHandle,
  recursiveMap,
  findItemById,
  filterTreeData
} from '@/hooks/use-floderMenu'
import { debounce } from '@/utils/tool'
import Prism from 'prismjs'

Prism.highlightAll()

const fileContent = ref<string>('')
const fileMenu = ref<FileMenu>([])
const inputValue = ref('')
let originMenu: FileMenu = []

const handleClick = async () => {
  try {
    const handle = await (window as any).showDirectoryPicker() //选择文件夹
    // const handle = await (window as any).showOpenFilePicker() //选择文件
    const root = await processHandle(handle) //文件根句柄
    originMenu = [root]
    fileMenu.value = recursiveMap([root])
  } catch (error) {
    console.log(error, '未能成功读取文件内容！')
  }
}
// 读取句柄文件
async function analysisFile(fileHandle: any) {
  const file = await fileHandle.getFile()
  const reader = new FileReader()
  reader.onload = (e) => {
    fileContent.value = e.target?.result as string
  }
  reader.readAsText(file, 'utf-8')
}

const floderMenuStore = useFloderMenuStore()
// 监听输入框过滤
const handleInput = (value: string) => {
  debounceFunction(value)
}
// 防抖包裹函数
const debounceFunction = debounce((value: string) => {
  const openMenu = filterTreeData(value, fileMenu.value, 'name')
  floderMenuStore.searchKeyword = value
  floderMenuStore.openMenu = openMenu
}, 100)

// 点击文件
const selectHandleItem = (item: any) => {
  const matchItem = findItemById(item.id, originMenu)
  analysisFile(matchItem)
}
</script>

<style scoped lang="less">
section {
  display: flex;
  justify-content: space-between;
  height: 90vh;
  nav {
    flex: 3;
    margin-right: 2px;
    overflow: auto;
    height: 100%;
  }
  main {
    flex: 7;
    overflow: auto;
    height: 100%;
  }
  .header_title {
    border: 1px solid #8df;
    border-radius: 5px;
  }
  .content {
    height: calc(100% - 30.6px);
    overflow: auto;
  }
  .floder {
    height: calc(100% - 62.6px);
  }
}
</style>
